package com.github.axet.audiorecorder.simple.services

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.MediaRecorder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import com.github.axet.audiorecorder.simple.R
import com.github.axet.audiorecorder.simple.activities.SimpleRecordingActivity
import com.github.axet.audiorecorder.simple.app.RecordingConfig
import com.github.axet.audiorecorder.simple.app.SimpleStorage
import java.io.File
import java.io.IOException

class SimpleRecordingService : Service() {
    
    companion object {
        private const val TAG = "SimpleRecordingService"
        private const val NOTIFICATION_ID = 1001
        private const val CHANNEL_ID = "recording_channel"
        
        const val ACTION_START_RECORDING = "START_RECORDING"
        const val ACTION_STOP_RECORDING = "STOP_RECORDING"
        const val ACTION_RECORDING_STATUS = "RECORDING_STATUS"
        
        const val EXTRA_RECORDING_TIME = "recording_time"
        const val EXTRA_RECORDING_FILE = "recording_file"
        const val EXTRA_ERROR_MESSAGE = "error_message"
        
        fun startRecording(context: Context) {
            val intent = Intent(context, SimpleRecordingService::class.java)
            intent.action = ACTION_START_RECORDING
            context.startService(intent)
        }
        
        fun stopRecording(context: Context) {
            val intent = Intent(context, SimpleRecordingService::class.java)
            intent.action = ACTION_STOP_RECORDING
            context.startService(intent)
        }
    }
    
    private var mediaRecorder: MediaRecorder? = null
    private var currentRecordingFile: File? = null
    private var isRecording = false
    private var recordingStartTime: Long = 0
    private var timeHandler: Handler? = null
    private var timeRunnable: Runnable? = null
    
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        timeHandler = Handler(Looper.getMainLooper())
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.action?.let { action ->
            when (action) {
                ACTION_START_RECORDING -> startRecording()
                ACTION_STOP_RECORDING -> stopRecording()
            }
        }
        return START_NOT_STICKY
    }
    
    private fun startRecording() {
        if (isRecording) {
            return
        }
        
        try {
            val storage = SimpleStorage(this)
            val config = RecordingConfig.fromPreferences(this)
            
            // 在开始录音前先检查和处理历史录音文件夹
            Log.d(TAG, "Starting recording - preparing storage and cleaning up old recordings...")
            prepareRecordingStorage(storage, config)
            
            currentRecordingFile = storage.getNewRecordingFile(config.audioFormat)
            
            mediaRecorder = MediaRecorder().apply {
                // 设置音频源为内部音频（如果支持）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
                } else {
                    setAudioSource(MediaRecorder.AudioSource.MIC)
                }
                
                // 设置输出格式和编码器
                when (config.audioFormat) {
                    "wav" -> {
                        setOutputFormat(MediaRecorder.OutputFormat.DEFAULT)
                        setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT)
                    }
                    "m4a" -> {
                        setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
                        setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
                    }
                    else -> {
                        // 默认使用 WAV 格式
                        setOutputFormat(MediaRecorder.OutputFormat.DEFAULT)
                        setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT)
                    }
                }
                
                setAudioSamplingRate(config.sampleRate)
                setOutputFile(currentRecordingFile?.absolutePath)
                
                prepare()
                start()
            }
            
            isRecording = true
            recordingStartTime = System.currentTimeMillis()
            
            startForeground(NOTIFICATION_ID, createRecordingNotification())
            startTimeUpdates()
            
            Log.d(TAG, "Recording started: ${currentRecordingFile?.absolutePath}")
            
        } catch (e: IOException) {
            Log.e(TAG, "Failed to start recording", e)
            sendErrorBroadcast("录音启动失败: ${e.message}")
            stopSelf()
        }
    }
    
    private fun stopRecording() {
        if (!isRecording) {
            return
        }
        
        try {
            mediaRecorder?.apply {
                stop()
                release()
            }
            mediaRecorder = null
            
            isRecording = false
            stopTimeUpdates()
            
            // 发送录音完成广播
            val intent = Intent(ACTION_RECORDING_STATUS)
            intent.putExtra("status", "stopped")
            intent.putExtra(EXTRA_RECORDING_FILE, currentRecordingFile?.absolutePath)
            sendBroadcast(intent)
            
            Log.d(TAG, "Recording stopped: ${currentRecordingFile?.absolutePath}")
            
        } catch (e: Exception) {
            Log.e(TAG, "Error stopping recording", e)
            sendErrorBroadcast("录音停止失败: ${e.message}")
        } finally {
            stopForeground(true)
            stopSelf()
        }
    }
    
    /**
     * 准备录音存储环境
     * 1. 检查和清理历史录音文件夹
     * 2. 确保今天的录音文件夹存在
     * 3. 记录存储状态信息
     */
    private fun prepareRecordingStorage(storage: SimpleStorage, config: RecordingConfig) {
        try {
            // 获取当前保留天数配置
            val retentionDays = config.retentionDays
            Log.d(TAG, "Recording retention policy: $retentionDays days")
            
            // 执行清理操作
            val startTime = System.currentTimeMillis()
            storage.cleanupOldRecordings()
            val cleanupTime = System.currentTimeMillis() - startTime
            Log.d(TAG, "Cleanup completed in ${cleanupTime}ms")
            
            // 确保今天的录音文件夹存在
            val todayFolder = storage.getTodayRecordingFolder()
            Log.d(TAG, "Today's recording folder: ${todayFolder.absolutePath}")
            
            // 获取存储统计信息
            val stats = storage.getRecordingStats()
            Log.i(TAG, "Storage stats: ${stats.fileCount} files, ${stats.folderCount} folders, ${stats.getFormattedSize()}")
            
        } catch (e: Exception) {
            Log.w(TAG, "Error during storage preparation", e)
            // 即使准备过程出错，也继续录音流程
        }
    }
    
    private fun startTimeUpdates() {
        timeRunnable = object : Runnable {
            override fun run() {
                if (isRecording) {
                    val recordingTime = System.currentTimeMillis() - recordingStartTime
                    
                    val intent = Intent(ACTION_RECORDING_STATUS)
                    intent.putExtra("status", "recording")
                    intent.putExtra(EXTRA_RECORDING_TIME, recordingTime)
                    sendBroadcast(intent)
                    
                    timeHandler?.postDelayed(this, 1000)
                }
            }
        }
        timeHandler?.post(timeRunnable!!)
    }
    
    private fun stopTimeUpdates() {
        timeRunnable?.let { runnable ->
            timeHandler?.removeCallbacks(runnable)
            timeRunnable = null
        }
    }
    
    private fun sendErrorBroadcast(errorMessage: String) {
        val intent = Intent(ACTION_RECORDING_STATUS)
        intent.putExtra("status", "error")
        intent.putExtra(EXTRA_ERROR_MESSAGE, errorMessage)
        sendBroadcast(intent)
    }
    
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "录音通知",
                NotificationManager.IMPORTANCE_LOW
            )
            channel.description = "显示录音状态"
            
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }
    
    private fun createRecordingNotification(): Notification {
        val intent = Intent(this, SimpleRecordingActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(this, CHANNEL_ID)
        } else {
            @Suppress("DEPRECATION")
            Notification.Builder(this)
        }
        
        return builder
            .setContentTitle("正在录音")
            .setContentText("点击返回录音界面")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build()
    }
    
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    
    override fun onDestroy() {
        super.onDestroy()
        if (isRecording) {
            stopRecording()
        }
    }
}